package com.ruoyi.common.utils;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.domain.BusinessParams;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.ruoyi.common.core.domain.entity.SysDictData;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;

public class MD5Util {
    private MD5Util(){}
    public static String byteArrayToHex(byte[] byteArray) {
        // 首先初始化一个字符数组，用来存放每个16进制字符
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        // new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））
        char[] resultCharArray = new char[byteArray.length * 2];
        // 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        // 字符数组组合成字符串返回
        return new String(resultCharArray);
    }

    public static String stringMD5(String input) {

        try {
            // 拿到一个MD5转换器（如果想要SHA1参数换成”SHA1”）
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 输入的字符串转换成字节数组
            byte[] inputByteArray = input.getBytes();
            // inputByteArray是输入字符串转换得到的字节数组
            messageDigest.update(inputByteArray);
            // 转换并返回结果，也是字节数组，包含16个元素
            byte[] resultByteArray = messageDigest.digest();
            // 字符数组转换成字符串返回
            return byteArrayToHex(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }

    }

    public static void main(String[] args) throws AlipayApiException {
        String str = "channelType=unionpay&money=100.00&notifyUrl=http://sisdn.com/Pay/notify/laotan&outTradeNo=20191001572448058161&returnUrl=http://sisdn.com/Pay/backurl/laotan&timestamp=1572448059044&token=bb084b1825b541e1871fbe7f38912dfe&uid=396353922362507264";
        System.out.println(stringMD5(str));
        String reqtime ="1733592402876";
        String url = "/easyhome-app-application/shop/order/addShopOrderListBySeller";
        String key = "NYApKFYLWsIHi1Baq9JKnPqm5D7t43RN";
        JSONObject ob = new JSONObject(true);
        ob.put("dwrsv","2.0.18");
        ob.put("requestTime",reqtime);

        String data = "{\"pickupName\":\"\",\"pickupPhone\":\"13458586855\",\"deliveryType\":\"1\",\"campaignIds\":[],\"shopGuideId\":\"1021233497383866368\",\"shopGuideName\":\"林思铖\",\"shopGuidePhone\":\"18344983492\",\"goodsDetailsList\":[{\"goodsSkuId\":\"1022352147997777920\",\"shopId\":\"1021233472930324480\",\"goodsCode\":\"0000000202372335\",\"goodsId\":\"1022352147939057664\",\"goodsSkuTitle\":\"得高 地板 实木地板\",\"goodsTitle\":\"得高 地板 实木地板\",\"goodsPrice\":\"646\",\"goodsPic\":\"iOS/Resources/25D2E896-67F4-4B67-A9B8-ED7DF5A2A908-1732859323687_829x1007.jpg\",\"goodsPicUrl\":\"https://ossprod.jrdaimao.com/iOS/Resources/25D2E896-67F4-4B67-A9B8-ED7DF5A2A908-1732859323687_829x1007.jpg\",\"deliveryTime\":\"2024-12-10\",\"goodsNum\":1,\"skillGoods\":false,\"skillPrice\":null,\"skillOrgPrice\":\"599\",\"equityTagsMap\":null,\"realPrice\":\"646\",\"needCalSkillGoods\":false}],\"dmcouponIdSet\":[],\"acMemberId\":\"\",\"isMember\":1,\"memberId\":\"1025426634775527424\",\"phone\":\"13458586855\",\"linkedCampaignId\":\"\",\"useVCards\":[],\"redCouponIdSet\":[],\"registerFlag\":false,\"deliveryTime\":\"2024-12-10\",\"usePump\":false,\"orderPumpMoney\":\"\",\"validateCode\":\"\",\"selectEasyWorker\":false,\"deviceSource\":\"h5Business\",\"apiVersion\":\"2.1.6\",\"engineeringOrder\":false,\"contractType\":1}";
        System.out.println("POST"+url+reqtime+ob.toJSONString()+data+key);
        System.out.println(stringMD5(stringMD5("POST"+url+reqtime+ob.toJSONString()+data+key)));
        String a = "time1731589273tokenuser:session:18e4518df87d4791845ea99a0af70d57{\"clientId\":\"3ac8549028657e0d8232f06037f88961\"}5e5ffe14a51f470ba309493692c43b19\n";
        a.replaceAll("\\s*", "").replaceAll("[^0-9a-zA-Z\\u4e00-\\u9f5a]", "");
        System.out.println(a);
//        System.out.println(BCrypt.hashpw("ldwallen", "$2a$10$YeGY5TyfZv9Mvv8.n5Wu8."));

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                "2021005184669678", "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCKkaBZMJ39bBlL7G8c4+9S6Xd/ComqaF/NTumfAKvCVVFf/c8jok8XrWyDpgy4CpL8IfRoDOrejpnqJ6jn5th0hjSXp9DtwzEeKsI+6jnKUw+WndBCPDBncz2Hn//yFb/7EE0AIf/+H+L8D5pvP2l9NNI4kyagm+Ds8gsOElPpOTGvS7Lhr5GwrDwRlAFnWHOp9FaKJhNGo9bM0uzQhmtIZ67EkxEz3NHdD2nHKOg+latblBb/gZFpd7gFJF677Jx+xfNM2uoXSrEVrFGW2qEbZ08a2QJGkCc/uey9Zx4JOiqAn7ThxBvmVP998Bc0P4/51X/IF7qCvgJHcZZt4UYvAgMBAAECggEAEbqaGm8295KaFfW1LawYFbKbQFzXyj66ayk6iMZsM1v5Il/13ahJmEzvAlT/cZigv7OUcq+caUczeBsE6E7HyPjWx8SH3bPImAR+f9A1/qXr66hbWe4bf1DmQXD+LToNKxEl2OuAtkHcJ8XTS4KAe62DbAufuJLZD1fUhENiCwe+fTWNpnvrnBm8wjP1+KzYQgb/xGmRR+yqhxxS9TYFayDjrsmSrz73XF0ai224/jQopojpBrGEAE8NnCXWKsc9vO0XwEOjR4U67ZvwKl1XpRQLZNz9lMBCcCeo5tHdA2HZqpIsbqXuj2E1D1iq+pEd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EcObbFBEFbObLjN6nqSxEEGE6VQeDDz+/HAoRidnm3F/kptOfT0+oizuD4Otw3dKi/zauLySblUf1siU/ilA5wuzS1R2PWUNjaOb4TwgJEgdyIe8U0mT+g3t11j2b9MNBoEjJE9PwE7qM9Zj2yWtZiNTTXf89WSMbmQcevrdRTEsrTjeZLKTmWXMR/JJDWkpDPLMp50V3xC46iOVMjIcTPQIDAQAB", "RSA2");
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        AlipayTradeCreateModel model = new AlipayTradeCreateModel();

        // 设置商户门店编号
//        model.setStoreId("NJ_001");

        // 设置业务扩展参数
//        ExtendParams extendParams = new ExtendParams();
//        extendParams.setSysServiceProviderId("2088511833207846");
//        model.setExtendParams(extendParams);

        // 设置订单标题
        model.setSubject("Iphone6 16G 49台");
//        SysDictData sysDictDataQuery = new SysDictData();
//        sysDictDataQuery.setDictType("zft_subject");
//        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictDataQuery);
//        Random random = new Random();
//        int index = random.nextInt(sysDictDataList.size());
//        SysDictData element = sysDictDataList.get(index);
//        model.setSubject(element.getDictLabel());
        // 设置商户操作员编号
//        model.setOperatorId("yx_001");

        // 设置产品码
        model.setProductCode("JSAPI_PAY");
        model.setOpAppId("2021005184669678");


//        // 设置订单附加信息
//        model.setBody("Iphone6 16G");
//
//        // 设置订单包含的商品列表信息
//        List<GoodsDetail> goodsDetail = new ArrayList<GoodsDetail>();
//        GoodsDetail goodsDetail0 = new GoodsDetail();
//        goodsDetail0.setGoodsName("ipad");
//        goodsDetail0.setQuantity(1L);
//        goodsDetail0.setPrice("2000");
//        goodsDetail0.setGoodsId("apple-01");
//        goodsDetail0.setGoodsCategory("34543238");
//        goodsDetail0.setCategoriesTree("124868003|126232002|126252004");
//        goodsDetail0.setShowUrl("http://www.alipay.com/xxx.jpg");
//        goodsDetail.add(goodsDetail0);
//        model.setGoodsDetail(goodsDetail);
//
//        // 设置商户的原始订单号
//        model.setMerchantOrderNo("20161008001");
//
//        // 设置可打折金额
//        model.setDiscountableAmount("80.00");

        // 设置商户订单号
        model.setOutTradeNo(System.currentTimeMillis()+"");

        // 设置订单总金额
        model.setTotalAmount("490000");

        // 设置商户传入业务信息
        BusinessParams businessParams = new BusinessParams();
//        businessParams.setMcCreateTradeIp(orderInfo.getOutBody());
        model.setBusinessParams(businessParams);
        model.setBuyerId("2088002606948690");
//
//        // 设置卖家支付宝用户ID
//        model.setSellerId("2088102146225135");
//
//        // 设置商户机具终端编号
//        model.setTerminalId("NJ_T_001");

        request.setBizModel(model);
//        request.setNotifyUrl("/notify/alipay/notifySucc");
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");
        System.out.println(JSONObject.toJSONString(request));
        AlipayTradeCreateResponse response = alipayClient.execute(request);
        System.out.println(JSONObject.toJSONString(response));
        String aa = "https://ds.alipay.com/?scheme="+URLEncoder.encode("alipays://platformapi/startapp?appId=2021005184669678&page=/pages/index/index"+ URLEncoder.encode("?tradeNO="+response.getTradeNo()));
        System.out.println(aa);

    }
}
